package com.group.transaction.config;

import com.group.transaction.domain.User;
import com.group.transaction.service.permission.PermissionService;
import com.group.transaction.service.user.UserSrevice;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.Set;

/**
 * @author YunXing Pang
 * @date 2019/7/28
 */
public class CustomRealm extends AuthorizingRealm {
    @Resource
    private UserSrevice userSrevice;

    @Resource
    private PermissionService permissionService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        Set<String> permissions = permissionService.selectValuesByUsername(username);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String loginName = (String) authenticationToken.getPrincipal();

        User user = userSrevice.selectUserByUsernameOrPhone(loginName);
        if (Objects.isNull(user)) {
            return null;
        }

        /*
         设置盐值
         */
        String salt = user.getSalt();
        ByteSource credentialsSalt = ByteSource.Util.bytes(salt);

        return new SimpleAuthenticationInfo(user, user.getPassword(), credentialsSalt, this.getName());
    }

    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 设置加密算法
        hashedCredentialsMatcher.setHashAlgorithmName("md5");
        // 设置加密次数
        hashedCredentialsMatcher.setHashIterations(2);
        // 设置是否通过盐值加密
        hashedCredentialsMatcher.setStoredCredentialsHexEncoded(true);
        super.setCredentialsMatcher(hashedCredentialsMatcher);
    }
}
